<?php


namespace app\controller\frontend;


use app\model\Category;
use app\model\CategorySubContent;
use app\model\SubContent;

class SearchController extends BaseController
{
    /**
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     * @throws \think\db\exception\DbException
     */
    public function search(Category $Category)
    {
        //拿到搜索页数据，主要为了拿seo数据
        $with=['thumbnail'=>function($q){
                $q->field('id,name,url,type');
            },'banner'=>function($q){
                $q->field('id,name,url,type');
            }
        ];
        $category = $Category->getCategory(['seller_id' => $this->sellerId, 'website_id' => $this->siteId ,'is_search' => 1],$with)['data']->toArray();
        $this->assign('current_cate',$category);

        //搜索
        $param = $this->request->param();
        $keywords = $param['q'];
        $this->assign('keywords',$keywords);

        //只查新闻
        $cateSub = new CategorySubContent();
        $cateSubWhere = [
            ['seller_id','=',$this->siteId],
            ['category_id','in',[7,8,9]]
        ];
        $cateSubCon = $cateSub->getAllCategorySubContent($cateSubWhere)['data'];
        $subIds = array_column($cateSubCon,'sub_content_id');

        $SubContent = new SubContent();
        $content = $SubContent->with(['thumbnail'=>function($q){
            $q->field('id,name,url,type');
        },'category'])->where(['seller_id'=>$this->sellerId,'is_del'=>1]);
        if(!empty($param['q'])){
            $content = $content -> whereLike('title','%' . $keywords . '%');
        }
        $param['siteId'] = $this->siteId;
        $param['sellerId'] = $this->sellerId;
        $data = $content->whereIn('id',$subIds)
            ->order('id','desc')
            ->paginate([
                'page' => $param['page'] ?? 0,
                'list_rows' => $param['limit'] ?? 10,
            ])->each(function (&$item)use($param){
                if(!empty($item['category'])) {
                    $item['category'] = $item->toArray()['category'];
                    $item['category_id'] = $item['category'][0]['id'];
                }
                $item['thumbnail'] = $item->toArray()['thumbnail'];
            });
        $data->appends(['q' => $keywords]);
        $this->assign('list', $data->items());
        $this->assign('list_page', $data->render());
        $template = $this->setTemplate('search');
        return $this->fetch($template);
    }
}